package main

import (
	"flag"
	"fmt"
	"github.com/valyala/fasthttp"
	"log"
	"math/rand"
	"net/http"
	"runtime"
	"time"

	"kop/framework/conf"
	"kop/libs/database"
	"kop/libs/redis"
	"kop/modules/sign_in/handler"
	"kop/modules/sign_in/models"
	log2 "kop/util/log"
)

func main() {

	runtime.GOMAXPROCS(runtime.NumCPU())
	rand.Seed(time.Now().UnixNano())

	conf.Init()
	log2.SetLevel(conf.Log.Level)

	if err := redis.Init(conf.Redis.Address, conf.Redis.MaxIdle, conf.Redis.MaxActive); err != nil {
		panic(err)
	}

	database.DB = database.Open(conf.DataBase.Dsn, conf.DataBase.MaxIdle, conf.DataBase.MaxOpen, conf.DataBase.Log)
	models.AutoMigrate()

	var port int
	flag.IntVar(&port, "p", 9999, "TCP port number to listen on (default: 9999)")
	flag.Parse()

	go checkRun(port)

	if err := fasthttp.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", port), h); err != nil {
		panic(err)
	}
}

func h(ctx *fasthttp.RequestCtx) {

	switch string(ctx.Path()) {

	case "/notice":

		handler.Notice(ctx)

	case "/login/baowan":

		handler.Login(ctx)

	case "/login/chuangku":

		handler.ChuangKu(ctx)

	default:
	}
}

func checkRun(port int) {

	for range time.NewTicker(time.Second).C {

		if _, err := http.Get(fmt.Sprintf("http://127.0.0.1:%d/login/test", port)); err == nil {
			log.Println("启动登陆服务器.")
			break
		}
	}
}
